package com.sengmitnick.timelogger;

import ohos.aafwk.content.IntentParams;
import ohos.aafwk.content.Operation;
import ohos.ace.ability.AceAbility;
import ohos.aafwk.content.Intent;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.utils.zson.ZSONObject;

import java.util.Base64;
import java.util.Objects;


public class PlusAbility extends AceAbility {
    private static final String JS_MODULE = "plus";
    private static final HiLogLabel LABEL = new HiLogLabel(HiLog.LOG_APP, 0, "MY_TAG");
    private String icon = "unknown";
    private String name = "未知状态";
    private String color = "#007DFF";

    @Override
    public void onStart(Intent intent) {
        intent.setParam("window_modal", 3);
        setInstanceName(JS_MODULE);
        Service.register(this);
        Boolean hasAuthorization = checkAuthorization();

        Object params = Objects.requireNonNull(intent.getParams()).getParam("__startParams");

        HiLog.info(LABEL, "PlusAbility: "+ ZSONObject.toZSONString(params));
        if (params != null) {
            ZSONObject startParams = ZSONObject.stringToZSON((String)params);
            icon = startParams.getString("icon");
            name = startParams.getString("name");
            color = startParams.getString("color");
        }

        IntentParams intentParams = intent.getParams();
        HiLog.info(LABEL, "PlusAbility: icon: "+icon+", name: "+name+", color: "+ color);

        if (intentParams != null) {
            intentParams.setParam("hasAuthorization", hasAuthorization);
            intentParams.setParam("icon", icon);
            intentParams.setParam("name", name);
            intentParams.setParam("color", color);
            setPageParams(null, intentParams);
        }
        super.onStart(intent);
    }

    @Override
    public void onStop() {
        super.onStop();
        Service.deRegister(this);
    }

    private Boolean checkAuthorization() {
        String Authorization = Service.getAuthorization();
        if (Authorization.length() <= 0) {
            Intent intent = new Intent();

            Operation operation = new Intent.OperationBuilder()
                    .withDeviceId("")
                    .withBundleName("com.sengmitnick.timelogger")
                    .withAbilityName("com.sengmitnick.timelogger.MainAbility")
                    .build();
            intent.setOperation(operation);
            startAbility(intent);
            return false;
        }
        return true;
    }
}
